<?php
class SuratKeluarController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column1', meaning
	 * using one-column layout. See 'protected/views/layouts/column1.php'.
	 */
	public $layout='//layouts/column1';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
	//		'rights',
		);
	}

	public function allowedActions() 
        { 
            return ''; 
        }
        
        public function actionPreview($id)
        {
            $surat  = $this->loadModel($id);
            
            $persetujuan = PersetujuanSuratKeluar::model()->findByAttributes(
                        array(
                            'id_surat_keluar' => $id
                        )
                    );
            
            $mPDF1 = Yii::app()->ePdf->mpdf();
 
        # You can easily override default constructor's params
        $mPDF1 = Yii::app()->ePdf->mpdf('', 'A5');
        
        # Load a stylesheet
        $stylesheet = file_get_contents(Yii::getPathOfAlias('webroot.css') . '/print_layout.css');
        $mPDF1->WriteHTML($stylesheet, 1);
 
        # renderPartial (only 'view' of current controller)
        $mPDF1->WriteHTML($this->renderPartial(
                        'preview', 
                        array(
                            'persetujuan' => $persetujuan,
                            'surat' => $surat
                        ),
                        true
                    ));
 
        # Renders image
        //$mPDF1->WriteHTML(CHtml::image(Yii::getPathOfAlias('webroot.css') . '/bg.gif' ));
 
        # Outputs ready PDF
        $mPDF1->Output();
            
        }
        
	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new SuratKeluar;

		// Uncomment the following line if AJAX validation is needed
		$this->performAjaxValidation($model);

		if(isset($_POST['SuratKeluar']))
		{
                    $transaction = Yii::app()->db->beginTransaction();

                    try{
                        
                        $model->attributes          =   $_POST['SuratKeluar'];
			$model->tanggal_pembuatan   =   date('Y-m-d H:i:s');
                        $model->id_pegawai          =   Yii::app()->user->id; //author
                        
                        if($model->save())
                        {
                            
                            foreach($_POST['pegawai'] as $key=>$value)
                            {
                                
                                $Persetujuan = new PersetujuanSuratKeluar;
                                $Persetujuan->id_pegawai        = $value;
                                $Persetujuan->sort              = $key;
                                $Persetujuan->id_surat_keluar   = $model->getPrimaryKey();
                                $Persetujuan->visible           = ($key==1) ? 1 : 0;
                                $Persetujuan->save();
                                
                            }
                            
                            
                            $PersetujuanCriteria = new CDbCriteria;
                            $PersetujuanCriteria->order = 'sort ASC';
                            $PersetujuanCriteria->limit = 1;
                            
                            $ListPersetujuan = PersetujuanSuratKeluar::model()->findByAttributes(
                                                    array(
                                                        'id_surat_keluar' => $model->getPrimaryKey()
                                                    ),
                                                    $PersetujuanCriteria
                                                );
                            
                            if(!$model->draft)
                            {
                                new SendMessage(
                                        Pegawai::model()->findByPk($ListPersetujuan->id_pegawai), 
                                        array(
                                                'url'           => '/persetujuanSuratKeluar/',
                                                'notifikasi'    => "Surat dengan nomor ".$model->no_surat." membutuhkan persetujuan anda.",
                                                'status'        => 0
                                            )
                                        ); 
                            }
                                
                        }
                        
                        $transaction->commit();
                        
                    }  catch (Exception $e){
                        
                        $this->debug($e);
                        $transaction->rollback();
                        Yii::app()->end();
                    }
			
                     $this->redirect(Yii::app()->createUrl('SuratKeluar'));
		}

		$this->render('create',array(
			'model'=>$model,
		));
	}

        public function actionApproval($id)
        { 
            $user   =  Yii::app()->getUser();
            
            
            $surat  = SuratKeluar::model()->findByPk($id, 'id_pegawai='.$user->id);
            
            $persetujuan = PersetujuanSuratKeluar::model()->findByAttributes(
                        array(
                            'id_pegawai' => $user->id,
                            'id_surat_keluar' => $id
                        )
                    );
            
            if($surat===NULL || $persetujuan===NULL)
            {
                throw new CHttpException(404,'Anda tidak diperbolehkan mengakses Surat ini');
            }
            
            $this->render(
                    'approval', 
                    array(
                        'persetujuan' => $persetujuan,
                        'surat' => $surat
                    )
                    );
        }
        
	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		 $this->performAjaxValidation($model);

		if(isset($_POST['SuratKeluar']))
		{
                    $transaction = Yii::app()->db->beginTransaction();

                    try{
                        
                        $model->attributes          =   $_POST['SuratKeluar'];
			$model->tanggal_pembuatan   =   date('Y-m-d H:i:s');
                        $model->id_pegawai          =   Yii::app()->user->id; //author
                        
                        if($model->save())
                        {
                            PersetujuanSuratKeluar::model()->deleteAllByAttributes(
                                            array(
                                                'id_surat_keluar' => $model->getPrimaryKey()
                                            )
                                        );
                                
                            
                            foreach($_POST['pegawai'] as $key=>$value)
                            {
                                
                                $Persetujuan = new PersetujuanSuratKeluar;
                                $Persetujuan->id_pegawai        = $value;
                                $Persetujuan->sort              = $key;
                                $Persetujuan->id_surat_keluar   = $model->getPrimaryKey();
                                $Persetujuan->visible           = ($key==1) ? 1 : 0;
                                $Persetujuan->save();
                                
                            }
                            
                            
                            $PersetujuanCriteria = new CDbCriteria;
                            $PersetujuanCriteria->order = 'sort ASC';
                            $PersetujuanCriteria->limit = 1;
                            
                            $ListPersetujuan = PersetujuanSuratKeluar::model()->findByAttributes(
                                                    array(
                                                        'id_surat_keluar' => $model->getPrimaryKey()
                                                    ),
                                                    $PersetujuanCriteria
                                                );
                            
                            if(!$model->draft)
                            {
                                new SendMessage(
                                        Pegawai::model()->findByPk($ListPersetujuan->id_pegawai), 
                                        array(
                                                'url'           => '/persetujuanSuratKeluar/',
                                                'notifikasi'    => "Surat dengan nomor ".$model->no_surat." membutuhkan persetujuan anda.",
                                                'status'        => 0
                                            )
                                        ); 
                            }
                                
                        }
                        
                        $transaction->commit();
                        
                    }  catch (Exception $e){
                        
                        $this->debug($e);
                        $transaction->rollback();
                        Yii::app()->end();
                    }
                    
                    $this->redirect(Yii::app()->createUrl('SuratKeluar'));
		}
                
                $PersetujuanSuratKeluar = PersetujuanSuratKeluar::model()->with('Pegawai')->findAllByAttributes(
                                                array(
                                                    'id_surat_keluar' => $model->id_surat_keluar
                                                )
                                            );
                
		$this->render('update',array(
			'model'=>$model,
                        'PersetujuanSuratKeluar' => $PersetujuanSuratKeluar
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		$this->loadModel($id)->delete();

		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
		if(!isset($_GET['ajax']))
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$model=new SuratKeluar('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['SuratKeluar']))
			$model->attributes=$_GET['SuratKeluar'];

		$this->render('index',array(
			'model'=>$model,
		));
	}

	

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=SuratKeluar::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='surat-keluar-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
